package com.uatair.web.task.mqtt.listener;

import com.alibaba.fastjson2.JSON;
import com.uatair.common.client.MqttMessageEvent;
import com.uatair.common.mqtt.domain.Content;
import com.uatair.common.mqtt.domain.MqttMessageDTO;
import com.uatair.common.mqtt.domain.OsdData;
import com.uatair.common.mqtt.domain.WuHuFlightData;
import com.uatair.common.mqtt.uploader.NanHangTaskUploader;
import com.uatair.common.mqtt.uploader.WuHuTaskUploader;
import com.uatair.system.domain.TpPurchaserSn;
import com.uatair.system.service.ITpPurchaserSnService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class MqttMessageListener {

    private static final Logger logger = LoggerFactory.getLogger(MqttMessageListener.class);

    private final ITpPurchaserSnService tpPurchaserSnService;

    private final WuHuTaskUploader wuHuTaskUploader;

    public MqttMessageListener(ITpPurchaserSnService tpPurchaserSnService, WuHuTaskUploader wuHuTaskUploader) {
        this.tpPurchaserSnService = tpPurchaserSnService;
        this.wuHuTaskUploader = wuHuTaskUploader;
    }

    @EventListener
    public void handleMqttMessage(MqttMessageEvent event) {
        String topic = event.getTopic();
        String message = event.getMessage();
        int qos = event.getQos();

        try {
            Content content = new Content();
            String[] split = topic.split("/");
            if (("thing").equals(split[0])){
                content = JSON.parseObject(message, Content.class);
            } else if ("connector".equals(split[0])) {
                // 1. 解析JSON字符串
                MqttMessageDTO mqttMessage = JSON.parseObject(message, MqttMessageDTO.class);
                content = mqttMessage.getContent();
            } else {
                return;
            }

            // 2. 检查是否为osd方法
            if ("osd".equals(content.getMethod())) {
                // 3. 获取osd数据

                // 4. 这里可以处理osdData，如存入数据库或转发
//                logger.info("飞机sn："+content.getDevice_id()+"的OSD数据: " + JSON.toJSONString(content));

                OsdData uavInfo = content.getData();
                if (uavInfo == null) {
                    return;
                }
                //1 filter dongtai data
                String deviceHardId = content.getGateway();
                if(StringUtils.isEmpty(deviceHardId)) {
                    deviceHardId = content.getDevice_id();
                    content.setGateway(deviceHardId);
                }
                TpPurchaserSn tpPurchaserSnWuhu = new TpPurchaserSn();
                tpPurchaserSnWuhu.setSn(deviceHardId);
                tpPurchaserSnWuhu.setPurchaser(2);
                tpPurchaserSnWuhu.setStatus("0");
                TpPurchaserSn isPurchaserWuhu = tpPurchaserSnService.selectSysPurchaserBySn(tpPurchaserSnWuhu);
                if (isPurchaserWuhu!=null)
                    wuHuTaskUploader.assembleFlightData(uavInfo, deviceHardId);
                // TODO: 添加你的业务逻辑
                NanHangTaskUploader nanHangTaskUploader = new NanHangTaskUploader();
                TpPurchaserSn tpPurchaserSn = new TpPurchaserSn();
                tpPurchaserSn.setSn(deviceHardId);
                tpPurchaserSn.setPurchaser(1);
                tpPurchaserSn.setStatus("0");
                TpPurchaserSn isPurchaser = tpPurchaserSnService.selectSysPurchaserBySn(tpPurchaserSn);
                if (isPurchaser==null) {
//                    log.error("南航未记录设备SN：{}", deviceHardId);
                    return;
                }
                String nanhangSN = isPurchaser.getPurchaserSn();
                if (StringUtils.isEmpty(nanhangSN)) {
//                    log.error("无对应南航设备SN：{}", deviceHardId);
                    return;
                }
                nanHangTaskUploader.sendData2Nanhang(content,uavInfo,nanhangSN);
            }  //此处处理电量 暂未处理
        } catch (Exception e) {
            logger.error("处理MQTT消息出错: {}", e.getMessage());
            e.printStackTrace();
        }
    }
}
